package com.g2room.driving.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.g2room.myuall.util.StringUtil;

public class ImageUtil {
	public static final String folder = Constants.localImgDir;

	public static void main(String[] args) {
		String a = "</section><p style=\"text-align: center;\"><img data-type=\"gif\" data-src=\"http://mmbiz.qpic.cn/mmbiz/rmUGBlbpVnomOIibnoE1IGINZ7BWiclqaOQ3nCqED6Cz8tkU9ztDIq3hIx40Dbu5M7HVFpkpf0rWkRjEnkdgSUiaQ/0?wx_fmt=gif\" data-ratio=\"1.0679611650485437\" data-w=\"206\"  /><br  /></p><section class=\"135editor\" data-id=\"8\" style=\"max-width: 100%; color: rgb(62, 62, 62); line-height: 28.4444px; white-space: normal; box-sizing: border-box !important; word-wrap: break-word !important; background-color: rgb(255, 255, 255);\"><h2 class=\"135brush\" data-brushtype=\"text\" style=\"margin-top: 10px; margin-bottom: 10px; padding-bottom: 5px; font-size: 24px; max-width: 100%; color: rgb(121, 56, 98); border-bottom-width: 1px; border-bottom-style: dotted; line-height: 29px; box-sizing: border-box !important; word-wrap: break-word !important;\"><strong><span style=\"max-width: 100%; font-size: 20px; box-sizing: border-box !important; word-wrap: break-word !important;\">方法一：去除轻微刮痕，用牙膏擦拭</span></strong></h2></section><p style=\"max-width: 100%; min-height: 1em; white-space: pre-wrap; color: rgb(62, 62, 62); line-height: 28.4444px; box-sizing: border-box !important; word-wrap: break-word !important; background-color: rgb(255, 255, 255);\"><br  /></p><section class=\"135editor\" data-id=\"3\" style=\"max-width: 100%; color: rgb(62, 62, 62); line-height: 28.4444px; white-space: normal; box-sizing: border-box !important; word-wrap: break-word !important; background-color: rgb(255, 255, 255);\"><section class=\"layout\" style=\"margin: 2px auto; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important;\"><section class=\"135brush\" data-style=\"color:rgb(89, 89, 89); font-size:14px; line-height:28px\" style=\"margin-top: -0.7em; padding: 10px 1em; max-width: 100%; box-sizing: border-box; font-size: 1em; border: 1px solid rgb(192, 200, 209); border-radius: 0.4em; color: rgb(51, 51, 51); word-wrap: break-word !important; background-color: rgb(239, 239, 239);\"><p style=\"max-width: 100%; min-height: 1em; white-space: pre-wrap; color: rgb(89, 89, 89); font-size: 14px; line-height: 28px; box-sizing: border-box !important; word-wrap: break-word !important;\"><br style=\"max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;\"  /></p><p style=\"max-width: 100%; min-height: 1em; white-space: pre-wrap; color: rgb(89, 89, 89); font-size: 14px; line-height: 28px; text-align: center; box-sizing: border-box !important; word-wrap: break-word !important;\"><img data-s=\"300,640\" data-type=\"jpeg\" data-src=\"http://mmbiz.qpic.cn/mmbiz/PfFCibB8LibtlkcXn8YbuRicQ1OicBiafnD3d0WKDFfz7D6vJdibw6tcTyNpQrzdY2icMA0D7fXibCJnM0J7Nmxh4FeoJw/0?wx_fmt=jpeg\" data-ratio=\"0.6507177033492823\" data-w=\"418\" data-src=\"http://mmbiz.qpic.cn/mmbiz/PfFCibB8LibtlkcXn8YbuRicQ1OicBiafnD3d0WKDFfz7D6vJdibw6tcTyNpQrzdY2icMA0D7fXibCJnM0J7Nmxh4FeoJw/640?wx_fmt=jpeg&amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1\" style=\"box-sizing: border-box !important; word-wrap: break-word !important; width: auto !important; visibility: visible !important;\"  /><br  /></p><p style=\"max-width: 100%; min-height: 1em; white-space: pre-wrap; color: rgb(89, 89, 89); font-size: 14px; line-height: 28px; box-sizing: border-box !important; word-wrap: break-word !important;\"><strong><span style=\"max-width: 100%; font-size: 16px; color: rgb(63, 49, 81); box-sizing: border-box !important; word-wrap: break-word !important;\">（1）将刮痕处清洗干净并晾干</span></strong></p><p style=\"max-width: 100%; min-height: 1em; white-space: pre-wrap; color: rgb(89, 89, 89); font-size: 14px; line-height: 28px; box-sizing: border-box !important; word-wrap: break-word !important;\"><strong><span style=\"max-width: 100%; font-size: 16px; color: rgb(63, 49, 81); box-sizing: border-box !important; word-wrap: break-word !important;\">（2）将毛巾打湿并涂上牙膏</span></strong></p><p style=\"max-width: 100%; min-height: 1em; white-space: pre-wrap; color: rgb(89, 89, 89); font-size: 14px; line-height: 28px; box-sizing: border-box !important; word-wrap: break-word !important;\"><strong><span style=\"max-width: 100%; font-size: 16px; color: rgb(63, 49, 81); box-sizing: border-box !important; word-wrap: break-word !important;\">（3）用力擦拭车上的刮痕</span></strong></p></section></section><section style=\"max-width: 100%; box-sizing: border-box; width: 0px; height: 0px; clear: both; word-wrap: break-word !important;\"></section></section><p><br  /></p><section class=\"wx96Diy\" data-source=\"bj.96weixin.com\">";
		a= "<p style=\"text-align: center\"><br> <img height=\"759\" width=\"600\" alt=\"\" src=\"/upload/webfile/2011/04/image/driving WAY.jpg\"></p> ";
		
		List<String> i = ImageUtil.getImgSrc(a, "src");
		for(String ii : i) {
			System.out.println(ii);
		}
	}
	/**
	 * 保存图片到指定文件夹
	 * @param urlStr
	 * @return	保存的文件名称
	 * @throws Exception
	 */
	public static String downloadImageByType(String urlStr, String dir) throws Exception {
		return downloadImage(urlStr, folder, "life", dir);
	}/**
	 * 保存图片到指定文件夹
	 * @param urlStr
	 * @return	保存的文件名称
	 * @throws Exception
	 */
	public static String downloadImage(String urlStr, String dir) throws Exception {
		return downloadImage(urlStr, folder, dir, null);
	}
	
	/**
	 * 
	 * @param urlStr
	 * @param folder	存放目录：E:/高绪国/资料/html/qgsh/images/
	 * @param path	相对目录，建议为每个抓取文章类型
	 * @param type	图片默认类型，为空则取连接后面的图片类型
	 * @return
	 * @throws Exception
	 */
	public static String downloadImage(String urlStr, String folder, String dir, String fileName) throws Exception {
	    // 构造URL
	    URL url = new URL(urlStr);
	    // 打开连接
	    URLConnection con = url.openConnection();
	    InputStream is = con.getInputStream();
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
//	    folder = HtmlUtil.getPath(folder) + dir;
	    File file = new File(folder + dir + "/");
	    if(!file.exists()) file.mkdirs();
	    if(null == fileName) fileName = urlStr.substring(urlStr.lastIndexOf("/") + 1);
	    String filePath = folder + dir + "/" + fileName;
	    File file1 = new File(filePath);
	    // 判断文件是否存在
	    if(file1.exists()) {
	    	return fileName;
	    }
	    // 输出的文件流
	    OutputStream os = new FileOutputStream(file1);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕，关闭所有链接
	    os.close();
	    is.close();
	    return filePath;
	}
	
	/**
	 * 提取图片的路径
	 * @param html
	 */
	public static List<String> getImgSrc(String html) {
		return getImgSrc(html, "src");
	}
	/**
	 * 提取图片的路径
	 * @param html	待提取的html内容
	 * @param srcField	图片标签属性
	 * @return
	 */
	public static List<String> getImgSrc(String html, String srcField) {
		List<String> imgSrcs = new ArrayList<String>(); 
		Document doc = Jsoup.parse(html);
		Elements srcEls = doc.getElementsByTag("img");
		for(Element srcEl : srcEls) {
			imgSrcs.add(srcEl.attr(srcField));
		}
		return imgSrcs;
	}
	
	/**
	 * 获取指定位数的随机数字
	 * 
	 * @param len  指定长度
	 * @return
	 * @auther <a href="mailto:gaoxuguo@stargame.com">高绪国</a>
	 */
	public static String genRandomCode(int len) {
		// 35是因为数组是从0开始的，26个字母+10个数字
		final int maxNum = 62;
		int i; // 生成的随机数
		int count = 0; // 生成的密码的长度
		char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
				'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
				'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
				'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		StringBuffer randomNum = new StringBuffer("");
		Random r = new Random();
		while (count < len) {
			// 生成随机数，取绝对值，防止生成负数，
			i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
			if (i >= 0 && i < str.length) {
				randomNum.append(str[i]);
				count++;
			}
		}
		return randomNum.toString();
	}
	
	public static Map<Integer, Integer> getImgWidth(String url) {
		Map<Integer, Integer> widthAndHeight = null;
		if(StringUtil.isEmpty(url)) return widthAndHeight;
		try {
	    	BufferedImage sourceImg =ImageIO.read(new URL(url));
	    	
	    	if(null != sourceImg) {
	    		widthAndHeight = new HashMap<Integer, Integer>();
	    		widthAndHeight.put(sourceImg.getWidth(), sourceImg.getHeight());
	    	}
	    } catch (Exception e) {
	    	System.out.println("获取图片错误：" + url);
	    	e.printStackTrace();
	    }
		return widthAndHeight;
	}
}
